package com.gable.exhibition.service.impl;

import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.dao.FileDao;
import com.gable.exhibition.dao.PartDao;
import com.gable.exhibition.model.Part;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.PartService;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.FileView;
import com.gable.exhibition.view.PartView;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Lesson on 2018/3/2.
 */
@Service("partService")
public class PartServiceImpl implements PartService {

    Logger logger =Logger.getLogger(this.getClass());

    @Autowired
    PartDao partDao;

    @Autowired
    FileDao fileDao;


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil savePartByBatch(List<PartView> list, User user,Long keyId,Long keyType) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(PartView pv : list){
            if(pv.getFlag() == 1){
                pv.setPartId(UUIDGenerator.getUniqueLong());
                pv.setCreateTime(df.format(new Date()));
                pv.setCreatePerson(user.getUserId());
                pv.setIsDel(0);
                pv.setKeyId(keyId);
                pv.setKeyType(keyType);
                partDao.insertSelective(pv);
                if(pv.getOldFileList() != null && pv.getOldFileList().size()>0){
                    for(FileView fileView : pv.getOldFileList() ){
                        fileView.setKeyId(pv.getPartId());
                        fileDao.updateByPrimaryKeySelective(fileView);
                    }
                }

                if(pv.getNewFileList() != null && pv.getNewFileList().size() > 0){
                    for(FileView fileView : pv.getNewFileList() ){
                        fileView.setKeyId(pv.getPartId());
                        fileDao.updateByPrimaryKeySelective(fileView);
                    }
                }

            }else if(pv.getFlag() == 3){
                Part part = partDao.selectByPrimaryKey(pv.getPartId());
                if(part != null){
                    part.setIsDel(1);
                    partDao.updateByPrimaryKeySelective(part);
                }
            }
        }
        return new ReturnResultUtil(200, MessageUtil.SAVESUCCESS);
    }

    @Override
    public ReturnResultUtil queryPart(PartView partView) {
        List<PartView> partViews = partDao.queryPart(partView);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,partViews);
    }
}
